<?php
/**
 * rbac.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2018/09/09
 * Time: 9:56
 */

/**
 * 代理模式（Proxy Pattern）
 */
class Permission {
    public function accessDecision(){
        return false;
    }
}
interface Role {
    public function cacheAccessDecision();
}
class DbRole implements Role {
    protected $ids;
    public function __construct($ids=''){
        $this->ids = $ids;
    }
    # Override
    public function cacheAccessDecision(){
        // session('access.node')
    }
}
class RoleProxy implements Role {
    private $dbRole;
    private $permission;
    public function __construct(DbRole $dbRole,Permission $permission){
        $this->dbRole = $dbRole;
        $this->permission = $permission;
    }
    /**
     * cacheAccessDecision
     * @override
     * @throws Exception
     */
    public function cacheAccessDecision(){
        if($this->permission->accessDecision()){
            // 权限通过，存储相关权限
            $this->dbRole->cacheAccessDecision();
        }
        // 权限未通过，抛出异常
        throw new Exception("访问权限被禁止");
    }
}

$dbRole = new DbRole();
$permission = new Permission();
try{
    $roleProxy = new RoleProxy($dbRole,$permission);
    $roleProxy->cacheAccessDecision();
}catch (Exception $e){
    echo $e->getMessage();
}
